<?php
App::import('Vendor', 'invoice');

if ($sorting[0][0] == 'product') { $sorting[0][0] = 'product_list'; }
else { $sorting[1][0] = 'product_list'; }

$arrange = ($sorting[1][0] == 'member') ? 'left' : 'right';
$by = ($sorting[0][0] == 'member') ? 'Co-Operator' : 'Product';
$for = 'Producer';
$subtitle = 'by ' . $by;

$data = array(
	'preferences' => array(
		'by' => $by,
		'desc' => 'Product',
		'for' => $for,
		'subtitle' => $subtitle,
		'contact' => $arrange,
		'2sided' => true
	)
);

//pr($lines);

$invoices = array();
$current = array('sections' => array());
$p = '';
$m = '';
$total = 0;
$r_total = 0;
$i_total = 0;
$t_total = 0;
$subTotal = 0;
$taxTotal = 0;
$surcharge = 0;
$m_fees_total = 0;
$flipper = -1;
$comp = '';
$df = '%B %e, %Y';
$mInfo = $this->requestAction('/members/getMemberInfo/' . $lines[0]['producer']['member_id']);
$current = array('sections'=>array());
$current['Member'] = array('first_name' => $mInfo['Member']['business_name']);
$current['Member']['address_line1'] = $mInfo['Member']['work_address_line1'];
$current['Member']['city'] = $mInfo['Member']['work_city'];
$current['Member']['state'] = $mInfo['Member']['work_state'];
$current['Member']['zip'] = $mInfo['Member']['work_zip'];
$current['Member']['home_phone'] = $mInfo['Member']['work_phone'];
$mtime = strtotime($mInfo['Member']['paid_fee'] . ' +' . Configure::read('Membership.valid_for'));
$ptime = strtotime(date('r', $mtime) . ' -' . Configure::read('Membership.ask_for_fee'));
$now = time();
$due = strftime($df,$mtime);
$member_message = '';
if ($now > $ptime) {
	$member_message = 'Your membership fee of $' . $mInfo['Member']['memb_amt_owed'] . ' will be due '. $due . '.  Your total is adjusted below, but you can wait until next month.';
} else if ($now > $mtime) {
	$member_message = 'Your membership fee of $' . $mInfo['Member']['memb_amt_owed'] . ' is due as of ' . $due . '.  Your total is adjusted below.';
} else {
	$member_message = 'Your membership is paid through ' . $due . '.';
}
$m_fee = ($now > $ptime) ? $mInfo['Member']['memb_amt_owed'] : 0;
$q_total = 0;
foreach ($lines as $line) {
	$comp = $line[$sorting[0][0]][$sorting[0][1]];
	if ($sorting[0][0]=='member') {
		$comp = $line['member']['first_name'] . ' ' . $comp;
	}
	if ($p != $comp) {
		if ($subTotal > 0) {
			if ($sorting[0][0] == 'product_list') {
				$current['sections'][$p][] = array('desc' => '<b>Total</b>', 'quantity' => $q_total, 'price' => '', 'weight' => '', 'tax' => '', 'total' => '$' . number_format($subTotal/100,2));
			}
			$subTotal = 0;
			$q_total = 0;
		}
		$current['sections'][$comp] = array();
		$p = $comp;
	}
	//calculate weight
	if ($line['basket_items']['weight'] == 0) {
		if ($line['product_list']['random_weight'] != 0) {
			if ($line['product_list']['minimum_weight'] == 0 && $line['product_list']['maximum_weight'] == 0) { // weights should not be averaged
				$line['basket_items']['weight'] = 1;
			} else {
				$line['basket_items']['weight'] = ($line['product_list']['minimum_weight'] + $line['product_list']['maximum_weight']) / 2;
			}
		}
	}
	//calculate total
	$line['subtotal'] = ($line['basket_items']['missing']) ? 0 : $line['orderables']['price'] * $line['basket_items']['quantity'];
	$line['subtotal'] = ($line['basket_items']['weight'] == 0) ? $line['subtotal'] : $line['subtotal'] * $line['basket_items']['weight'];
	$line['tax'] = ($line['product_list']['tax_exempt']) ? 0 : $line['subtotal'] * SALES_TAX;
	$m_comp = ($sorting[1][0] == 'member') ? $line[$sorting[1][0]][$sorting[1][1]] . ', ' . $line['member']['first_name'] : $line[$sorting[1][0]][$sorting[1][1]];
	if (($m != $m_comp) || ($r_total == 0)) {
		$m = ($sorting[1][0] == 'member') ? $line[$sorting[1][0]][$sorting[1][1]] . ', ' . $line['member']['first_name'] : $line[$sorting[1][0]][$sorting[1][1]];
	}
	//echo $sorting[1][0],$sorting[1][1];
	//echo 'BN: '. $line[$sorting[1][0]][$sorting[1][1]];
	//array('desc'=>'Eggs, Medium Brown - Free Range','quantity' => '5','price' => '$2.25/dozen','weight' => 'N/A','tax' => '$0.00','total' => '$11.25'),
	$t_line = array();
	$t_line['desc'] = ($line['basket_items']['missing']) ? '<i>' . $m . '</i>' : $m;
	$t_line['quantity'] = ($line['basket_items']['missing']) ? 0 : $line['basket_items']['quantity'];
	$t_line['price'] = '$' . number_format($line['orderables']['price'],2) . '/' . $line['orderables']['priced_by'];
	$w = ($line['basket_items']['weight'] == 0) ? 'N/A' : number_format($line['basket_items']['weight'],2) . ' ' . $line['orderables']['priced_by'] . '(s)';
	$t_line['weight'] = $w;
	$t_line['tax'] = '$' . number_format($line['tax'],2);
	$t_line['total'] = '$' . number_format($line['subtotal'] + $line['tax'],2);
	
	$q_total += $t_line['quantity'];
	
	$current['sections'][$p][] = $t_line;
	$tot = round($line['subtotal']*100);
	$tax = round($line['tax']*100);
	//$total += $line['subtotal'] + $line['tax'];
	$i_total += $tot;
	$t_total += $tax;
	$r_total += ($tot+$tax)/100;
	$subTotal += $tot;
	//$r_total += $line['subtotal'] + $line['tax'];
	$taxTotal += $tax;
}
if ($sorting[0][0] == 'product_list') {
	$current['sections'][$p][] = array('desc' => '<b>Total</b>', 'quantity' => $q_total, 'price' => '', 'weight' => '', 'tax' => '', 'total' => '$' . number_format($subTotal/100,2));
}


$a_total = 0;
foreach($notes as $note) {
	$a_total += $note['Note']['adj_amount'] * 100;
}
$surcharge = $flipper * round($i_total * (PROD_SURCHARGE/100));
$inv_total = (($i_total + $a_total + $surcharge + $t_total)/100);


$current['totals'] = array(
    'sub' => '$' . number_format($i_total/100,2),
    'surcharge' => '$' . number_format($surcharge/100,2),
    'm_fee' => '$' . number_format($flipper * $m_fee,2),
    'adj' => '$' . number_format($a_total/100,2),
    'tax' => '$' . number_format($t_total/100,2),
    'final' => '$' . number_format($inv_total + ($flipper * $m_fee),2),
	'message' => $member_message
);
$invoices[] = $current;

$data['Invoices'] = $invoices;
//echo '<pre>';
//print_r($data);
//echo '</pre>';
//$total += $inv_total;

$I = new InvoicePDF();
$I->run($data);

if (!Configure::read('renderPdfs')) {
	$pdfcode = $I->output(1);
	$pdfcode = r("\n","\n<br>",htmlspecialchars($pdfcode));
	e('<html>');
	e("<body>");
	e('<pre>');
	print_r($data);
	e(trim($pdfcode));
	e('</pre>');
	e("</body>");
	e('</html>');
} else {
	$I->ezStream(array('Content-Disposition' => 'invoice-' . $producer['Producer']['producer_id'] . '.pdf'));
}
?>